package com.yinhe.music.yhmusic.album.list;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.yinhe.music.common.utils.ScreenUtils;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.event.RxbusNullObject;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.adapter.AlbumAdapter;
import com.yinhe.music.yhmusic.album.info.AlbumInfoActivity;
import com.yinhe.music.yhmusic.base.BaseModel;
import com.yinhe.music.yhmusic.base.BasePresenter;
import com.yinhe.music.yhmusic.base.BaseServiceViewPagerFragment;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.model.AlbumInfo;
import com.yinhe.music.yhmusic.search.ISearchFragment;
import com.yinhe.music.yhmusic.utils.UmengEventUtils;
import com.yinhe.music.yhmusic.widget.CustomLoadMoreView;
import com.yinhe.music.yhmusic.widget.DividerItemDecoration;
import com.yinhe.music.yhmusic.widget.WrapContentLinearLayoutManager;

import java.util.List;

import butterknife.BindView;

import static com.yinhe.music.yhmusic.constants.IConstants.FAV_ALBUM;
import static com.yinhe.music.yhmusic.constants.IConstants.INSTRUMENT_ALBUM;
import static com.yinhe.music.yhmusic.constants.IConstants.SEARCH_ALBUM_LIST;
import static com.yinhe.music.yhmusic.constants.IConstants.SINGER_DETAIL_ALBUM;

/**
 * 专辑列表界面
 * @author hasee
 * @date 2017/2/25
 */

public class AlbumFragment extends BaseServiceViewPagerFragment implements ISearchFragment,
        BaseQuickAdapter.OnItemClickListener, IAlbumListContract.IAlbumListView {

    @BindView(R.id.recommend_music_recyclerview)
    RecyclerView mRecyclerView;

    private TextView mAlbumNum;
    private AlbumAdapter mAdapter;
    private int type;
    private int singerid;
    private String key;
    private DividerItemDecoration itemDecoration;
    private LinearLayout mHeaderLayout;
    private int mPageSize = 10;
    private int mPage = 1;
    private int pageNum;

    AlbumListPresenter mPresenter;

    /**
     * 实例化构造方法
     *
     * @param from 专辑列表属于的页面
     * @param id   singerId
     * @return 实例化AlbumFragment
     */
    public static AlbumFragment newInstance(int from, int id, String key) {
        AlbumFragment fragment = new AlbumFragment();
        Bundle bundle = new Bundle();

        bundle.putInt("album_from", from);
        bundle.putInt("id", id);
        bundle.putString("key", key);

        fragment.setArguments(bundle);
        return fragment;
    }

    RecyclerView.OnScrollListener listener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                RxBus.get().post(RxBusEventType.Search.HIDE_SOFT_KEYBOARD, RxbusNullObject.INSTANCE);
            }
        }
    };

    @Override
    public BasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    public void initPresenter() {
        mPresenter = new AlbumListPresenter();
        mPresenter.attachModelView(new BaseModel(), this);
    }

    @Override
    public void initView() {
        RxBus.get().register(this);

        if (getArguments() != null) {
            type = getArguments().getInt("album_from", -1);
            singerid = getArguments().getInt("id", -1);
            key = getArguments().getString("key");
        }
        setRecyclerView();
    }

    @Override
    public int getLayoutId() {
        return R.layout.music_hall_recycler_layout;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        try {
            RxBus.get().unregister(this);
        }catch (Throwable e) {
            Log.e("RxBus解绑=============", e.toString());
        }
    }

    @Override
    protected void onFragmentFirstVisible() {
        if (mService != null) {
            mPage = 1;
            reqAlbumList();
        }
    }

    private void reqAlbumList() {
        switch (type) {
            case FAV_ALBUM:
                mPresenter.getCollectAlbumList(mPage, mPageSize);
                break;
            case SINGER_DETAIL_ALBUM:
            case INSTRUMENT_ALBUM:
                mPresenter.getSingerAlbumList(type, mPage, mPageSize, singerid);
                break;
            case SEARCH_ALBUM_LIST:
                mPresenter.getSearchAlbumList(mPage, mPageSize, key);
                break;
            default:
                mPresenter.getAlbumList(mPage, mPageSize);
                break;
        }
    }

    private void setRecyclerView() {
        if (type == IConstants.NEW_ALBUM_LIST) {
            GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
            mRecyclerView.setLayoutManager(gridLayoutManager);
        } else {
            itemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST, ScreenUtils.dp2px(20), false);
            mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
            mRecyclerView.addItemDecoration(itemDecoration);
        }

        mRecyclerView.setHasFixedSize(true);

        if (type == IConstants.SEARCH_ALBUM_LIST) {
            mRecyclerView.addOnScrollListener(listener);
        }

        initAdapter();
    }

    /**
     * 初始化adapter
     */
    private void initAdapter() {
        mAdapter = type == IConstants.SEARCH_ALBUM_LIST
                ? new AlbumAdapter(key)
                : new AlbumAdapter();
        mAdapter.setOnItemClickListener(this);
        mAdapter.setLoadMoreView(new CustomLoadMoreView());
        mAdapter.setOnLoadMoreListener(() -> {
            if (mPage <= pageNum) {
                reqAlbumList();
            } else {
                mAdapter.loadMoreEnd();
            }
        }, mRecyclerView);
        mAdapter.setPreLoadNumber(4);

        if (type == FAV_ALBUM) {
            View mHeadView = getHeadView();
            mAdapter.addHeaderView(mHeadView);
        }

        mRecyclerView.setAdapter(mAdapter);
    }

    /**
     * 设置专辑列表头部
     *
     * @return view
     */
    private View getHeadView() {
        if (mRecyclerView != null) {
            View view = getLayoutInflater().inflate(R.layout.header_musiclist, (ViewGroup) mRecyclerView.getParent(), false);

            ImageView mPlayIcon = view.findViewById(R.id.play_icon);
            TextView mPlayText = view.findViewById(R.id.play_text);
            mAlbumNum = view.findViewById(R.id.play_num);
            LinearLayout mManagerLayout = view.findViewById(R.id.manager);
            mHeaderLayout = view.findViewById(R.id.header_layout);

            mHeaderLayout.setVisibility(View.GONE);
            mPlayIcon.setVisibility(View.GONE);
            mPlayText.setVisibility(View.GONE);
            mManagerLayout.setVisibility(View.GONE);
            return view;
        }
        return null;
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (position < adapter.getData().size()) {
            if (type == IConstants.SEARCH_ALBUM_LIST) {
                UmengEventUtils.clickSearch(getActivity(), UmengEventUtils.ALBUM);
            }
            AlbumInfo albumInfo = (AlbumInfo) adapter.getData().get(position);
            Intent intent = new Intent(getActivity(), AlbumInfoActivity.class);
            intent.putExtra("albumId", albumInfo.getAlbumId());
            startActivity(intent);
        }
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.Album.COLLECT_ALBUM)
    )
    public void onRxbusUpdateAlbum(String id) {
        if (type == FAV_ALBUM){
            mPage = 1;
            reqAlbumList();
        }
    }

    @Override
    public void updateDataForKey(String key) {
        if (key.equals(this.key)) {
            return;
        }
        this.key = key;
        mPage = 1;
        if (mAdapter != null) {
            mAdapter.setSearchKey(key);
            reqAlbumList();
        }
    }

    @Override
    public void setAlbumListUI(AlbumInfo albumInfo) {
        mRecyclerView.stopScroll();
        List<AlbumInfo> list = albumInfo.getAlbumList();
        if (list == null) {
            return;
        }

        for (AlbumInfo info : list) {
            info.setItemType(type == IConstants.NEW_ALBUM_LIST
                    ? AlbumInfo.NEW_ALBUM_LSIT
                    : AlbumInfo.OTHER_ALBUM_LSIT);
        }

        this.pageNum = albumInfo.getPageNum();

        if (mPage == 1) {
            if (type == FAV_ALBUM) {
                mHeaderLayout.setVisibility(View.VISIBLE);
                mAlbumNum.setText(String.format("收藏的专辑(%s)", String.valueOf(albumInfo.getCollectNum())));
            }
            mAdapter.setEmptyView(getEmptyView(mRecyclerView));
        }

        int size = list.size();

        if (mPage == 1) {
            mAdapter.setNewData(list);
        }
        if (mPage > 1 && size > 0) {
            mAdapter.addData(list);
        }
        if (mPage >= pageNum) {
            mAdapter.loadMoreEnd();
        } else {
            mPage++;
            mAdapter.loadMoreComplete();
        }
    }

    @Override
    public void setLoadMoreFailUI() {
        mAdapter.loadMoreFail();
    }
}
